<template>
  <view class="container">
    <span class="banbenhao-dianhua" @click="showActionSheet('18947472919')"
      >{{
        storedVersion ? '当前版本：V' + storedVersion + '|' : ''
      }}
      📞值班电话：18947472919</span
    >
    <view class="mainBox">
      <view class="greetings">国源公司智慧园区</view>
      <uni-forms
        ref="form"
        class="formBox"
        :modelValue="formData"
        :rules="rules"
      >
        <uni-forms-item name="phonenumber" ref="input">
          <view class="uni-form-item itemBox">
            <image class="img" src="/static/image/login_user.png" />
            <uni-easyinput
              type="text"
              v-model="formData.phonenumber"
              placeholder="请输入手机号"
              :inputBorder="false"
              @blur="(e) => $refs.input.onFieldChange(e.detail.value)"
            />
          </view>
        </uni-forms-item>
        <uni-forms-item name="password">
          <view class="uni-form-item itemBox">
            <image class="img" src="/static/image/login_pwd.png" />
            <uni-easyinput
              type="password"
              v-model="formData.password"
              placeholder="请输入密码"
              :inputBorder="false"
            />
          </view>
        </uni-forms-item>
        <uni-forms-item name="smsCode">
          <view class="uni-form-item itemBox">
            <image class="img" src="/static/image/login_code.png" />
            <uni-easyinput
              v-model="formData.smsCode"
              placeholder="短信验证码"
              :inputBorder="false"
            />

            <button
              type="text"
              size="mini"
              class="blue-text"
              :class="{ active: gettingSmsCode }"
              @click="getSmsCodeFn"
            >
              {{
                gettingSmsCode ? '重新获取(' + smsSecond + ')' : '获取验证码'
              }}
            </button>
          </view>
        </uni-forms-item>
      </uni-forms>

      <view class="btnBox">
        <view class="tip" v-show="showTip">
          <uni-icons type="info-filled" color="#F44698" size="16"></uni-icons>
          <text>账号或密码输入错误</text>
        </view>
        <button class="submit" type="primary" @click="formSubmit">登录</button>
      </view>
    </view>
    <view class="footer"> </view>
  </view>
</template>

<script>
import {
  login,
  getCode,
  getRoleMenu,
  getSmsCode,
  latestVersion,
} from '@/api/index';
export default {
  data() {
    return {
      uuid: '',
      codeImg: '',
      // 提交错误提示
      showTip: false,
      // 短信验证码
      timer: null,
      gettingSmsCode: false,
      smsSecond: 60,
      // 表单数据
      formData: {
        phonenumber: uni.getStorageSync('userInfo').phonenumber || '',
        password: uni.getStorageSync('userInfo').password || '',
      },
      rules: {
        phonenumber: {
          rules: [
            {
              required: true,
              errorMessage: '请输入手机号',
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              errorMessage: '请输入正确的手机号码',
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: '请输入密码',
            },
          ],
        },
        smsCode: {
          rules: [
            {
              required: true,
              errorMessage: '请输入验证码',
            },
          ],
        },
      },
      storedVersion: uni.getStorageSync('appVersion'),
    };
  },
  onLoad(query) {
    // 初始化存储版本（优先使用本地存储的版本）
    this.storedVersion = uni.getStorageSync('appVersion') || '1.0.0';

    // 获取当前应用版本
    plus &&
      plus.runtime.getProperty(plus.runtime.appid, (info) => {
        const currentVersion = info.version;

        // 版本不一致时更新存储
        if (this.compareVersions(currentVersion, this.storedVersion)) {
          this.clearCache();
          uni.setStorageSync('appVersion', currentVersion);
          this.storedVersion = currentVersion;
        }

        // 确保在此回调内获取最新版本
        this.getLatestVersion();
      });
  },
  onUnLoad() {
    this.timer && this.clearTimer();
  },
  onShow() {},
  methods: {
    clearCache() {
      // 清理逻辑（参考方法一的实现）
      if (plus.os.name === 'Android') {
        let main = plus.android.runtimeMainActivity();
        let cacheDir = main.getCacheDir();
        let files = plus.android.invoke(cacheDir, 'listFiles');
        files.forEach((file) => {
          let filePath = '' + file;
          plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
            if (entry.isDirectory) {
              entry.removeRecursively(); // 递归删除子目录
            } else {
              entry.remove();
            }
          });
        });
      } else {
        plus.cache.clear(); // iOS/H5 清理缓存
      }
    },
    // 正确的版本比较方法（支持多级版本号）
    compareVersions(v1, v2) {
      const v1Parts = v1.split('.').map(Number);
      const v2Parts = v2.split('.').map(Number);

      for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
        const part1 = v1Parts[i] || 0;
        const part2 = v2Parts[i] || 0;
        if (part1 !== part2) {
          return part1 > part2;
        }
      }
      return false; // 版本相等
    },

    getLatestVersion() {
      latestVersion()
        .then(({ data }) => {
          if (!data?.appVersion) return;

          // 使用正确的比较方法
          if (this.compareVersions(data.appVersion, this.storedVersion)) {
            uni.showModal({
              title: '更新提示',
              content: '发现新版本，是否立即更新？',
              confirmText: '去更新',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  this.handleUpdate(data.downloadAddress);
                }
              },
            });
          }
        })
        .catch(console.error);
    },

    handleUpdate(downloadUrl) {
      if (!downloadUrl) {
        uni.showToast({ icon: 'none', title: '下载地址错误，请联系管理员' });
        return;
      }

      plus.runtime.openURL(downloadUrl, (err) => {
        uni.showToast({ title: '跳转失败:' + err.message, icon: 'none' });
      });
    },
    // 跳转页面
    onLocation(url) {
      uni.navigateTo({
        url,
      });
    },
    // 获取短信验证码
    getSmsCodeFn() {
      this.$refs.input.onFieldChange(this.formData.phonenumber).then((res) => {
        if (res && res.errorMessage) {
          uni.showToast({
            icon: 'none',
            title: res.errorMessage,
          });
        } else {
          // if (this.gettingSmsCode) return;
          this.smsSecond = 60;
          this.gettingSmsCode = true;
          this.timer = setInterval(() => {
            this.smsSecond--;
            if (this.smsSecond < 1) {
              this.gettingSmsCode = false;
              this.smsSecond = 60;
              this.timer && this.clearTimer();
            }
          }, 1000);
          getSmsCode(this.formData.phonenumber)
            .then((res) => {})
            .catch((err) => {
              console.log('err', err);
              let msg = '网络错误，请重试！';
              if (typeof err == 'string') {
                try {
                  var obj = JSON.parse(str);
                  if (obj && typeof obj === 'object' && obj !== null) {
                    msg = obj.msg || obj.errMsg;
                  } else {
                    msg = err;
                  }
                } catch (e) {
                  msg = err;
                }
              } else if (Array.isArray(err) && err.length && err[0].msg) {
                msg = err[0].msg;
              } else if (err && err.msg) {
                msg = err.msg;
              } else if (err.errMsg) {
                msg = err.errMsg;
              }
              console.log(err);
              this.timer && this.clearTimer();
              this.gettingSmsCode = false;
              uni.showToast({
                icon: 'none',
                title: msg || '网络错误，请重试！',
              });
            });
        }
      });
    },
    // 提交
    formSubmit() {
      this.$refs['form']
        .validate()
        .then((res) => {
          uni.showLoading({
            title: '登录中',
          });
          login({
            clientId: 'e5cd7e4891bf95d1d19206ce24a7b32e',
            tenantId: '000000',
            grantType: 'sms',
            phonenumber: res.phonenumber,
            password: res.password,
            smsCode: res.smsCode,
          })
            .then(async (loginRes) => {
              const userInfo = JSON.stringify({
                phonenumber: res.phonenumber,
                password: res.password,
              });
              // storage
              uni.setStorageSync('token', loginRes.data.access_token);
              uni.setStorageSync('clientid', loginRes.data.client_id);
              uni.setStorageSync('userInfo', userInfo);
              // menuInfo
              getRoleMenu().then((res) => {
                uni.setStorageSync('menu', res.data); // 提示并跳转
                uni.hideLoading();
                uni.showToast({
                  title: `登录成功`,
                  success: () => {
                    setTimeout(() => {
                      uni.reLaunch({
                        url: '/pages/index/index',
                      });
                    }, 1000);
                  },
                });
              });
            })
            .catch((err) => {
              console.log('err', err);
              uni.hideLoading();
              if (err.code == 410) {
                uni.reLaunch({
                  url: '/pages/login/editPassword',
                });
              }
            });
        })
        .catch((err) => {
          console.log('err', err);
          // uni.showToast({
          //     icon: 'none',
          //     title: `密码或账号错误，请重新输入`,
          // })
        });
    },
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    // 显示操作菜单
    showActionSheet(phoneNumber) {
      uni.showActionSheet({
        itemList: ['呼叫', '复制'],
        success: (res) => {
          const index = res.tapIndex;
          if (index === 0) {
            this.makePhoneCall(phoneNumber);
          } else if (index === 1) {
            this.copyToClipboard(phoneNumber);
          }
        },
        fail: () => {
          // 用户点击了取消
        },
      });
    },
    // 拨打电话
    makePhoneCall(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber: phoneNumber.toString(),
        success: () => {
          console.log('成功调起拨号面板');
        },
        fail: (err) => {
          console.error('拨打电话失败:', err);
        },
      });
    },

    // 复制到剪贴板
    copyToClipboard(text) {
      uni.setClipboardData({
        data: text.toString(),
        success: () => {
          uni.showToast({
            title: '复制成功',
            icon: 'none',
          });
        },
        fail: (err) => {
          console.error('复制失败:', err);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - var(--window-top) - 128rpx);
  padding: 64rpx 36rpx;
  background-image: url('/static/image/login_bg.png');
  background-repeat: no-repeat;
  background-size: 100% auto;
  position: relative;
  ::v-deep .gengxin-tishi .uni-dialog-button.uni-border-left {
    display: none !important;
  }
  .banbenhao-dianhua {
    position: fixed;
    bottom: 10rpx;
    right: 40rpx;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.5);
    font-style: italic;
    z-index: 999;
  }
  .mainBox {
    margin: 280rpx 34rpx 0;
    background: #ffffff;
    border-radius: 18rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-between;
    .blue-text {
      display: inline-block;
      min-width: 100rpx;
      color: #1777fb;
      &.active {
        color: #c1c1c1;
      }
    }
    .greetings {
      font-size: 35rpx;
      font-weight: 600;
      color: #1777fb;
      line-height: 47rpx;
      padding: 54rpx 0 40rpx;
    }
    :deep(.uni-forms) {
      padding: 0 40rpx;
    }
    .itemBox {
      width: calc(100% - 44rpx);
      padding: 15rpx 22rpx;
      border-radius: 4rpx;
      border: 2rpx solid #d9d9d9;
      background: #fff;
      display: flex;
      align-items: center;
      .img {
        width: 38rpx;
        height: 38rpx;
      }
      .code {
        width: 160rpx;
        height: 60rpx;
        border-radius: 5rpx;
        background: #e6e6e6;
      }
    }
    .btnBox {
      width: 80%;
      button {
        font-size: 36rpx;
        margin: 32rpx auto 54rpx;
        line-height: 90rpx;
        letter-spacing: 5rpx;
        box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(0, 0, 0, 0.25);
        border-radius: 45rpx;
        &::after {
          border: none;
        }
      }
      .tip {
        height: 32rpx;
        color: #f2358e;
        font-size: 22rpx;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: center;
        text {
          padding-left: 20rpx;
        }
      }
      .submit {
        background: linear-gradient(83deg, #549df3 0%, #1876e9 88%);
      }
    }
    .toolBox {
      color: #888888;
      font-size: 24rpx;
      font-weight: bold;
      display: flex;
      align-items: center;
      view:first-child {
        color: #2d7ee0;
      }
      .line {
        height: 22rpx;
        border: 1rpx solid #c1c1c1;
        margin: 0 43rpx;
      }
    }
    ::v-deep .uni-forms-item__label {
      display: none;
    }
    ::v-deep .uni-forms-item__error {
      left: 55rpx;
    }
  }
}
.third {
  margin: 195rpx auto 84rpx;
  .box {
    margin-bottom: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .line {
      width: 24%;
      border: 3rpx solid #cfcdcd;
    }
    .text {
      color: #c1c1c1;
      font-size: 24rpx;
      font-weight: bold;
      padding: 0 30rpx;
    }
  }
  .wcLogin {
    width: 83rpx;
    height: 83rpx;
    color: #fff;
    margin: auto;
    background: #50b674;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 165rpx;
  .agreement {
    color: #888888;
    font-size: 24rpx;
    font-weight: bold;
    text-align: center;
    text {
      color: #2d7ee0;
    }
  }
}
</style>
